/*
 * @Filename: UserController.java
 * @CreateTime: 2015-11-13 14:16:44
 * @Version: 1.0
 * @All rights (are) reserved.
 * @author miklechun
 */
package com.wonders.qxmanager.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wonders.qxmanager.base.Parameter;
import com.wonders.qxmanager.model.User;
import com.wonders.qxmanager.service.UserService;
import com.wonders.qxmanager.utils.PageArrayList;
import com.wonders.qxmanager.utils.PageUIHelper;
import com.wonders.qxmanager.utils.PageUIHelper.Page;
import javax.servlet.http.HttpSession;

/**
 * user web控制器
 * 
 * @author miklechun
 * 
 */
@Controller
public class UserController {

	@Autowired
	private UserService userService;
	List<User> list;

	@RequestMapping("/user/index.do")
	public ModelAndView index(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		return new ModelAndView("/user/list.jsp");
	}

	@RequestMapping("/user/login.do")
	public void login(User user, HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		HttpSession session = req.getSession();
		
		// 获取session的Id
		String sessionId = session.getId();
		// 判断session是不是新创建的
		if (session.isNew()) {
			System.out.println("session创建成功，session的id是：" + sessionId);
		} else {
			System.out.println("服务器已经存在该session了，session的id是：" + sessionId);
		}
		/*
		 * List<User> list=userService.getListBySQL(sqllogin, parameter2); if
		 * (list!=null) { list=userService.getListBySQL(sqllogin, parameter2);
		 * if (list!=null) { return new ModelAndView("pages/index"); } else {
		 * System.out.println("密码错误！！！"); } } else {
		 * System.out.println("用户名不存在"); }
		 */

		Map<String, Object> result = new HashMap<String, Object>();
		/*
		 * String account = req.getParameter("account"); String password =
		 * req.getParameter("password");
		 */
		String sqlaccount = "from User where account=:p0";
		String sqllogin = "from User where account=:p1 and password=:p2";
		Object[] Para = { user.getAccount(), user.getPassword() };
		Parameter parameter1 = new Parameter();
		parameter1.put("p0", user.getAccount());
		Parameter parameter2 = new Parameter(Para);
		if (StringUtils.isNotBlank(user.getAccount())
				&& StringUtils.isNotBlank(user.getPassword())) {
			list = userService.getListByHQL(sqlaccount, parameter1);
			if (list != null && list.size() != 0) {
				list = userService.getListByHQL(sqllogin, parameter2);
				if (list != null && list.size() != 0) {
					for (User loginUser : list) {
						// 将数据存储到session中
						session.setAttribute("userid", loginUser.getUserid());
						session.setAttribute("username", loginUser.getAccount());
					}
					result.put("success", true);
					result.put("msg", "登录成功!");
				} else {
					result.put("success", false);
					result.put("msg", "密码错误");
				}

			} else {
				result.put("success", false);
				result.put("msg", "用户不存在!");
			}

		} else {
			result.put("success", false);
			result.put("msg", "用户名和密码不允许为空!");
		}

		PageUIHelper.writeJsonResponse(res, JSONObject.fromBean(result)
				.toString());
		// return new ModelAndView("/pages/index.jsp");
	}

	@RequestMapping("/user/info.do")
	public ModelAndView info(HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		return new ModelAndView("/user/info.jsp");
	}

	@RequestMapping("/user/save.do")
	public void save(HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		req.setCharacterEncoding("UTF-8");
//		User user = new User();
//		user.setAccount(req.getParameter("account"));
//		user.setName(req.getParameter("name"));
//		user.setPassword(req.getParameter("password"));
//		user.setImage(req.getParameter("image"));
//		userService.addUser(user);
		
		Long s1=System.currentTimeMillis();
		
		for(int i=0;i<5000;i++){
			User user = new User();
			user.setAccount("a"+i);
			user.setName("b"+i);
			user.setPassword("c"+i);
			user.setImage("d"+i);
			user.setSex("e"+i);
			user.setBirthday(new Timestamp(1));
			user.setTelephone(new BigDecimal(12));
			user.setEmail("h");
			user.setAddress("i"+i);
			user.setUserid(new BigDecimal(12));
			user.setRoleid(new BigDecimal(12));
			user.setLeader("l"+i);
			user.setOrganizationid(new BigDecimal(12));
			user.setPower("n"+i);
			userService.addUser(user);
		}
		Long s2=System.currentTimeMillis();
		System.out.println("开始时间："+s1);
		System.out.println("结束时间："+s2);
		System.out.println("s2-s1="+(s2-s1));
		
		System.out.println("每插入一个用时:"+(double)(s2-s1)/5000);
		
		PageUIHelper.writeFormResponse(res, "{errorMsg:true}");
	}

	/*
	 * @RequestMapping("/user/search.do") public void search(HttpServletRequest
	 * req, HttpServletResponse res) throws Exception { BigDecimal id = new
	 * BigDecimal(req.getParameter("itemid")); User user =
	 * userService.getUserById(id); Page page = PageUIHelper.getPage(req);
	 * PageArrayList<User> list = userService.getListByPage(user, page);
	 * PageUIHelper.writeJsonResponse(res, PageUIHelper.toString(list)); }
	 */

	@RequestMapping("/user/delete.do")
	public void remove(HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		System.out.println(req.getParameter("id"));
		userService.deleteUser(new BigDecimal(req.getParameter("id")));
		PageUIHelper.writeFormResponse(res, "{errorMsg:true}");
	}

	@RequestMapping("/user/edit.do")
	public void edit(User user, HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		req.setCharacterEncoding("UTF-8");
		System.out
				.println(req.getParameter("userid") + "==" + user.getUserid());
		System.out.println(user.getAccount() + "" + user.getImage()
				+ "###############");
		String sqledit = "UPDATE User set account=:p1,password=:p2,name=:p3,image=:p4 WHERE userId=:p0";
		Parameter parameter1 = new Parameter();
		parameter1.put("p0", user.getUserid());
		parameter1.put("p1", user.getAccount());
		parameter1.put("p2", user.getName());
		parameter1.put("p3", user.getPassword());
		parameter1.put("p4", user.getImage());

		/*
		 * user.setUserid(user.getUserid()); user.setAccount(user.getAccount());
		 * user.setImage(user.getPassword());
		 * user.setPassword(user.getPassword());
		 */
		userService.updateUser(sqledit, parameter1);
		PageUIHelper.writeFormResponse(res, "{errorMsg:true}");
	}

	@SuppressWarnings("null")
	@RequestMapping("/user/list.do")
	public void list(HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		HttpSession session = req.getSession();
		req.setCharacterEncoding("UTF-8");
		User user = new User();
		PageArrayList<User> list = null;
		Page page = PageUIHelper.getPage(req);
		String itemid = req.getParameter("itemid");
		System.out.println(itemid);
		if (itemid != null && StringUtils.isNotBlank(itemid)) {
			String sqlbyid = "from User where account=:p0";
			Parameter parameter1 = new Parameter();
			parameter1.put("p0", itemid);
			user = userService.getUserByHQL(sqlbyid, parameter1);
			// 乐乐提示
			list = new PageArrayList<User>(1, 1, 1);
			list.add(user);
			//
			//
		} else {
			list = userService.getListByPage(user, page);
			List listTest=userService.getAll();//查看内存变化用的(没有用)

		}
		PageUIHelper.writeJsonResponse(res, PageUIHelper.toString(list));
	}
}
